package com.yuzai.reading.commons.interceptor;

import cn.hutool.core.util.ObjectUtil;
import com.yuzai.reading.commons.context.BaseContext;
import com.yuzai.reading.commons.exception.TokenParseException;
import com.yuzai.reading.entitys.UserEntity;
import com.yuzai.reading.mappers.UserMapper;
import com.yuzai.reading.properties.JwtProperties;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
@Slf4j
public class CheckInterceptor implements HandlerInterceptor {


    @Autowired
    private JwtProperties jwtProperties;

    @Autowired
    private UserMapper userMapper;


    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //判断当前拦截到的是Controller的方法还是其他资源
        if (!(handler instanceof HandlerMethod)) {
            //当前拦截到的不是动态方法，直接放行
            return true;
        }
        String username = BaseContext.getCurrentId();
        //是否存在该用户
        UserEntity userEntity = userMapper.selectUserById(username);
        if (ObjectUtil.isNull(userEntity)) {
            throw new TokenParseException("账号不存在，请注册账号");
        }
        String token = request.getHeader(jwtProperties.getTokenName());
        //存在验证token
        if (!userEntity.getToken().equals(token)) {
            //不相同
            throw new TokenParseException("当前账号已在别的地方登录，请重新登录");
        }

        //expire是否过期
        if (System.currentTimeMillis() / 1000 > userEntity.getExpire()) {
            throw new TokenParseException("会员过期，请重新开通");
        }

        return true;
    }
}
